import { Request, Response } from 'express'
import { createNewGame, makeMove } from '../models/Game'

// 存储游戏状态（实际应用中应使用数据库）
const games: { [gameId: string]: any } = {}

export const createGame = (req: Request, res: Response) => {
  const gameId = Math.random().toString(36).substring(2, 10)
  games[gameId] = createNewGame()
  res.json({ gameId })
}

export const handleMove = (req: Request, res: Response) => {
  const { cellIndex, currentPlayer, board } = req.body

  // 验证请求
  if (typeof cellIndex !== 'number' || !['X', 'O'].includes(currentPlayer) || !Array.isArray(board)) {
    return res.status(400).json({ error: 'Invalid request' })
  }

  // 创建游戏状态
  const game = {
    board,
    currentPlayer,
    gameActive: true,
    winner: null
  }

  // 处理移动
  const newGame = makeMove(game, cellIndex)

  res.json(newGame)
}